//
//  HomeViewController.m
//  DriverFramework
//
//  Created by Qianxia on 2017/1/3.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "BaseViewController.h"
#import "HomeViewController.h"
#import "OrdersViewController.h"
#import <QXUtils/QXUtils-umbrella.h>
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <QXYangqilingDriverOfMy/QXYangqilingDriverOfMy-umbrella.h>
#import <DriverLoginManager/DriverLoginManager-umbrella.h>
#import <QXYueYueModels/QXYueYueModels-umbrella.h>
#import "BaseViewControllerTitleView.h"
#import <QXSocketManager/QXSocketManager.h>
#import "ConfigureKeyHeader.h"
#import <DriverLoginManager/DriverLoginViewController.h>
#import <QXSocketManager/QXSocketManager.h>
#import "HeaderMacro.h"
#import <QXDataManager/QXDataManager.h>
#import <DriverLoginManager/LoginManageServices.h>
#import "NotificationNameManager.h"
@interface BaseViewController ()<UIScrollViewDelegate>
/// 底层滚动视图
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/// 标题View
//@property (weak, nonatomic) IBOutlet UIView *titleView;

@property (weak, nonatomic) IBOutlet BaseViewControllerTitleView *titleView;


/// 标题底部视图间隔
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleBottomViewCenterMargin;

/// 是否加载过视图
@property (assign, nonatomic) BOOL isLoadedView;

/// 首页视图
@property (strong, nonatomic) HomeViewController *homeViewController;
/// 订单视图
@property (strong, nonatomic) OrdersViewController *ordersViewController;
/// 我的视图
@property(nonatomic , strong) DriverOfMyViewController *driverOfMyViewController;



/// 顶部导航栏三个按钮
@property (weak, nonatomic) IBOutlet UIButton *mineButton;
@property (weak, nonatomic) IBOutlet UIButton *homeButton;
@property (weak, nonatomic) IBOutlet UIButton *orderButton;


/**
 存放 scrollView 子控制器的view
 */
@property (weak, nonatomic) IBOutlet UIView *rootView;


@end

@implementation BaseViewController

/**
 初始化导航栏
 
 @return 底层导航栏
 */
+ (UINavigationController *)baseNavigationController {
    static UINavigationController *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Root" bundle:nil];
        
        instance = [storyboard instantiateViewControllerWithIdentifier:@"BaseNavigationController"];
    });
    
    return instance;
}

#pragma mark - Life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationData];
    
    [self addDriverLoginNotification];
    
    [self registerNotificationUserAccountIsSealed];
    
    QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (!driverModel) {
        
        [self.navigationController pushViewController:[LoginManageServices getDriverLoginViewControllerWithDriverType:[[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]] animated:NO];
    }else {
        
        if ([driverModel.isFirst isEqualToString:@"1"]) { // 如果是首次登录进入登录页面
            
            [self.navigationController pushViewController:[LoginManageServices getDriverLoginViewControllerWithDriverType:[[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]] animated:NO];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

#pragma mark - 司机登录登出通知
- (void)addDriverLoginNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverLoginSuccess:) name:DriverLoginSucessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(driverLoginout:) name:DriverLoginOutSucessNotification object:nil];
}

// 登录成功
- (void)driverLoginSuccess:(NSNotification *)notification {
    
    QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    [QXDataManager saveValue:[NSString stringWithFormat:@"%d" , driverModel.type] forKey:QXDriverTypeKey];
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// 退出登录
- (void)driverLoginout:(NSNotification *)notification {
    
    [[QXSocketManager manager] close];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"QXYY_UserDriverModelKey"];
    
    id lastVC = self.navigationController.viewControllers.lastObject;
    if (![lastVC isKindOfClass:[DriverLoginViewController class]]) {
        
        [self.navigationController pushViewController:[LoginManageServices getDriverLoginViewControllerWithDriverType:[[QXDataManager getValueForKey:QXDriverTypeKey] integerValue]] animated:YES];
    }
}

#pragma mark - 用户账号被封通知
- (void)registerNotificationUserAccountIsSealed {
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userAccountIsSealedAction:) name:NotificationName_UserAccountIsSealed object:nil];
}

- (void)userAccountIsSealedAction:(NSNotification *)aNotification {
    
    if ([aNotification.name isEqualToString:NotificationName_UserAccountIsSealed]) {
        
        NSString *reasonStr = [NSString stringWithFormat:@"%@" , aNotification.object];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"账号已被封" message:reasonStr preferredStyle:(UIAlertControllerStyleAlert)];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"联系客服" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {

            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@" , [QXDataManager getValueForKey:User_KeyWord_CustomerServiceTel]]];
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                
                
            }];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"我知道了" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self presentViewController:alertVC animated:YES completion:nil];
        });
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    // scrollView滚动到中间
    if (!self.isLoadedView) {
        
        // 显示首页
        [self.scrollView setContentOffset:CGPointMake(DeviceScreenWidth, 0) animated:NO];
        
        self.isLoadedView = YES;
    }
}

#pragma mark - 初始化数据

/**
 *  初始化数据
 */
- (void)initializationData {
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 设置标题栏
    self.titleView.frame = CGRectMake(0, 0, DeviceScreenWidth, 44);
    self.titleBottomViewCenterMargin.constant = (self.titleView.frame.size.width) / 3;

    self.scrollView.contentSize = CGSizeMake(DeviceScreenWidth * 3, DeviceScreenHeight);
    
    // 设置中心按钮高亮
    [self.homeButton setImage:[QXDriverConfiguration imageWithName:@"nav_logo_gray"] forState:UIControlStateNormal];
    [self.homeButton setImage:[QXDriverConfiguration imageWithName:@"nav_logo_light"] forState:UIControlStateHighlighted];
    
    /// 建立父子关系_我的
    self.driverOfMyViewController = [DriverOfMyViewController shareInstance];
    [self addChildViewController:self.driverOfMyViewController];
    [self.scrollView addSubview:self.driverOfMyViewController.view];
    [self.driverOfMyViewController didMoveToParentViewController:self];
    
    self.driverOfMyViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
    self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:self.driverOfMyViewController.view attribute:(NSLayoutAttributeTop) multiplier:1.0 constant:0]];
    [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView attribute:(NSLayoutAttributeLeft) relatedBy:(NSLayoutRelationEqual) toItem:self.driverOfMyViewController.view attribute:(NSLayoutAttributeLeft) multiplier:1.0 constant:0]];
    [self.scrollView addConstraint:[NSLayoutConstraint constraintWithItem:self.scrollView attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.driverOfMyViewController.view attribute:(NSLayoutAttributeBottom) multiplier:1.0 constant:0]];
    [self.driverOfMyViewController.view addConstraint:[NSLayoutConstraint constraintWithItem:self.driverOfMyViewController.view  attribute:(NSLayoutAttributeWidth) relatedBy:(NSLayoutRelationEqual) toItem:nil attribute:(NSLayoutAttributeNotAnAttribute) multiplier:1.0 constant:width]];
    
    
    
    // 建立父子关系
    self.homeViewController = [HomeViewController homeViewInstance];
    [self addChildViewController:self.homeViewController];
    [self.scrollView addSubview:self.homeViewController.view];
    [self.homeViewController didMoveToParentViewController:self];
    
    self.homeViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *viewsDictionary = @{@"view": self.homeViewController.view};
    [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(width)-[view]-(width)-|" options:0 metrics:@{@"width":@(DeviceScreenWidth)} views:viewsDictionary]];
    [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:viewsDictionary]];
    
    // 建立父子关系
    self.ordersViewController = [OrdersViewController ordersViewInstance];
    [self addChildViewController:self.ordersViewController];
    [self.scrollView addSubview:self.ordersViewController.view];
    [self.ordersViewController didMoveToParentViewController:self];
    
    self.ordersViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
    NSDictionary *viewsDictionary1 = @{@"view": self.ordersViewController.view};
    [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(width)]|" options:0 metrics:@{@"width":@(DeviceScreenWidth)} views:viewsDictionary1]];
    [self.scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:viewsDictionary1]];

    
    
}



#pragma mark - IBAction

/**
 顶部标题点击事件

 @param sender sender description
 */
- (IBAction)titleTabSelected:(UIButton *)sender {
    
    // 点击滚动视图
    NSInteger index = sender.tag - 100;
    [self.scrollView setContentOffset:CGPointMake(DeviceScreenWidth * index, 0) animated:YES];
    [self reloadTitleViewStatusWithIndex:index];
}

/**
 刷新顶部标题视图

 @param index 位置
 */
- (void)reloadTitleViewStatusWithIndex:(NSInteger)index {
    self.mineButton.highlighted = self.mineButton.tag == 100 + index;
    self.homeButton.highlighted = self.homeButton.tag == 100 + index;
    self.orderButton.highlighted = self.orderButton.tag == 100 + index;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (self.scrollView == scrollView) {
        
        CGPoint point = scrollView.contentOffset;
        CGFloat width = CGRectGetWidth(self.titleView.frame);
        
        CGFloat value = (point.x - DeviceScreenWidth) / (DeviceScreenWidth * 2) * (width / 4 ) * 3;
        // 刷新状态
        NSInteger index = (NSInteger)round(point.x / DeviceScreenWidth);
        [self reloadTitleViewStatusWithIndex:index];
        self.titleBottomViewCenterMargin.constant = value;
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
